//
//  XMGWebViewController.m
//  BuDeJie
//
//  Created by xiaomage on 16/3/16.
//  Copyright © 2016年 小码哥. All rights reserved.
//

#import "XMGWebViewController.h"
#import <WebKit/WebKit.h>
#import "HWjiluYaoQingliuzhangViewController.h"
#import "HWanGame-Swift.h"
#import "UIBarButtonItem+Item.h"


@interface XMGWebViewController ()<WKUIDelegate,WKNavigationDelegate, WKScriptMessageHandler>
{
    UIButton *jiluBut;
}
@property (weak, nonatomic) IBOutlet UIView *contentView;
@property (weak, nonatomic) IBOutlet WKWebView *webView;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *backItem;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *forwardItem;
@property (weak, nonatomic) IBOutlet UIProgressView *progressView;
@property (weak, nonatomic) IBOutlet UIToolbar *toolbarView;
@property (weak, nonatomic) NSString *groupId;
@property (assign, nonatomic) BOOL isPaySuccess;

@end

@implementation XMGWebViewController

- (IBAction)goBack:(id)sender {
    [self.webView goBack];
}
- (IBAction)goForward:(id)sender {
    [self.webView goForward];
}
- (IBAction)reload:(id)sender {
    [self.webView reload];
}

#pragma mark - 生命周期方法
- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    
    //    _webView.frame = self.contentView.bounds;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
    //    [[NSURLCache sharedURLCache] removeAllCachedResponses];
    
    NSArray * types =@[WKWebsiteDataTypeMemoryCache,WKWebsiteDataTypeDiskCache]; // 9.0之后才有的
    /*
     NSArray *type = @[WKWebsiteDataTypeDiskCache,       // 磁盘缓存
     WKWebsiteDataTypeMemoryCache,     // 内存缓存
     WKWebsiteDataTypeOfflineWebApplicationCache, // HTML 离线 Web 应用程序缓存。
     WKWebsiteDataTypeCookies,         // Cookies
     WKWebsiteDataTypeSessionStorage,  // HTML 会话存储
     WKWebsiteDataTypeLocalStorage,    // HTML 本地存储
     WKWebsiteDataTypeWebSQLDatabases, // WebSQL 数据库
     WKWebsiteDataTypeIndexedDBDatabases, // IndexedDB 数据库
     ];
     */
    NSSet *websiteDataTypes = [NSSet setWithArray:types];
    NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
    [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{
        
    }];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    // 添加webView
    
    if (self.isGroup == YES) {
        UIImage *loginImg = [UIImage imageNamed:@"fanxiangdeicotupian"];
        loginImg = [loginImg imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        jiluBut = [UIButton buttonWithType:UIButtonTypeCustom];
        jiluBut.frame = CGRectMake(0, 0, 30, 44);
        jiluBut.backgroundColor = [UIColor clearColor];
        jiluBut.layer.cornerRadius = 2;
        // [jiluBut setTitle:@"记录" forState:UIControlStateNormal];
        [jiluBut addTarget:self action:@selector(fenxiangTap:) forControlEvents:UIControlEventTouchUpInside];
        [jiluBut setImage:loginImg forState:UIControlStateNormal];
        jiluBut.hidden = YES;
        jiluBut.layer.masksToBounds = YES;
        //        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:jiluBut];
        self.navigationItem.rightBarButtonItems = @[[[UIBarButtonItem alloc]initWithCustomView:jiluBut],[UIBarButtonItem  backItemWithimage:[UIImage imageNamed:@"webRefresh"] highImage:[UIImage imageNamed:@"webRefresh"] target:self action:@selector(webViewRefresh) title:@""]];
    } else {
        self.navigationItem.rightBarButtonItems = @[[UIBarButtonItem  backItemWithimage:[UIImage imageNamed:@"webRefresh"] highImage:[UIImage imageNamed:@"webRefresh"] target:self action:@selector(webViewRefresh) title:@""]];
    }
    
    WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
    configuration.userContentController = [[WKUserContentController alloc] init];
    [configuration.userContentController addScriptMessageHandler:self name:@"gameinfo"];
    
    
    WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:configuration];
    _webView = webView;
    _webView.UIDelegate = self;
    _webView.navigationDelegate = self;
    [self.contentView addSubview:webView];
    
    [self.progressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.mas_equalTo(0);
        make.height.mas_equalTo(2);
    }];
    
    self.navigationItem.leftBarButtonItems = @[[UIBarButtonItem  backItemWithimage:[UIImage imageNamed:@"fanhui"] highImage:[UIImage imageNamed:@"fanhui"] target:self action:@selector(back) title:@"   "],[UIBarButtonItem  backItemWithimage:[UIImage imageNamed:@"webClose"] highImage:[UIImage imageNamed:@"webClose"] target:self action:@selector(webViewClose) title:@"   "]];
    
    
    
    self.toolbarView.hidden = YES;
    
    if (self.isPay) {
        NSString *tStr = [NSString stringWithFormat:@"%ld",[WMUtil getTimeSp]];
        
        NSString *sign = [NSString stringWithFormat:@"%@%@%@",[HWLocallyStoredData getLoginUserID],tStr,@"fsd213ewdsadqwe2121213edsad"];
        
        NSString *signMD5 = [WMUtil md5HexDigest:sign];
        NSString *urlStr = [NSString stringWithFormat:@"%@api/app/v3/?ct=coin&uid=%@&t=%@&sign=%@&language=%@", [HWOCGlobalConst baseUrl], [HWLocallyStoredData getLoginUserID],tStr,signMD5,[HWjianzhiduiObject returnLanguageAcquisition]];
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
        [webView loadRequest:request];
    } else {
        NSURLRequest *request = [NSURLRequest requestWithURL:_url];
        [webView loadRequest:request];
    }
    // 展示网页
    
    
    // KVO监听属性改变
    /*
     Observer:观察者
     KeyPath:观察webView哪个属性
     options:NSKeyValueObservingOptionNew:观察新值改变
     
     KVO注意点.一定要记得移除
     */
    [webView addObserver:self forKeyPath:@"canGoBack" options:NSKeyValueObservingOptionNew context:nil];
    [webView addObserver:self forKeyPath:@"canGoForward" options:NSKeyValueObservingOptionNew context:nil];
    [webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil];
    // 进度条
    [webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    [webView addObserver:self forKeyPath:@"URL" options:NSKeyValueObservingOptionNew context:nil];
    
    [webView mas_makeConstraints:^(MASConstraintMaker *make) {
        if (SCREEN_HEIGHT < 812) {
            make.top.mas_equalTo(44);
        }else {
            make.top.mas_equalTo(88);
        }
        
        make.left.right.bottom.mas_equalTo(0);
    }];
    
    
    
}

- (void)back {
    if ([self.url.absoluteString containsString:@"ac=huiyuan"]) {
        [self.navigationController popViewControllerAnimated:YES];
    }else {
        if (self.isPaySuccess) {
            [self.navigationController popViewControllerAnimated:YES];
        }else {
            if (self.webView.canGoBack == YES) {
                [self.webView goBack];
            } else {
                [self.navigationController popViewControllerAnimated:YES];
            }
        }
    }
    
}

- (void)webViewClose {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)webViewRefresh {
    [self.webView reload];
}

- (void)fenxiangTap:(UIButton *)sender {
    HWCloseGroupView *closeGroupView = [[HWCloseGroupView alloc] init];
    closeGroupView.groupId = self.groupId;
    [closeGroupView show];
    closeGroupView.close = ^{
        [self.navigationController popViewControllerAnimated:YES];
    };
}
// 只要观察对象属性有新值就会调用
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"URL"]) {
        // 可以在这里进行拦截并做相应的处理
        NSLog(@"URL------%@",_webView.URL.absoluteString);
        if ([_webView.URL.absoluteString containsString:@"ct=qun&ac=info"]) {
            //            if ([_webView.URL.absoluteString containsString:@"ct=qun&ac=info&app=1"]) {
            //                NSArray *array = [_webView.URL.absoluteString componentsSeparatedByString:@"ct=qun&ac=info&app=1&id="];
            //                NSArray *array1 = [array[1] componentsSeparatedByString:@"&"];
            //                self.groupId = array1[0];
            //                jiluBut.hidden = NO;
            //            }else if ([_webView.URL.absoluteString containsString:@"ct=qun&ac=info&type=1"]) {
            //                NSArray *array = [_webView.URL.absoluteString componentsSeparatedByString:@"ct=qun&ac=info&type=1&id="];
            //                NSArray *array1 = [array[1] componentsSeparatedByString:@"&"];
            //                self.groupId = array1[0];
            //                jiluBut.hidden = NO;
            //            }else{
            //                NSArray *array = [_webView.URL.absoluteString componentsSeparatedByString:@"ct=qun&ac=info&id="];
            //                NSArray *array1 = [array[1] componentsSeparatedByString:@"&"];
            //                self.groupId = array1[0];
            //                jiluBut.hidden = NO;
            //            }
            NSArray *array = [_webView.URL.absoluteString componentsSeparatedByString:@"&"];
            [array enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
                NSLog(@"%@",obj);
                if ([obj containsString:@"id="]){
                    self.groupId = [obj substringFromIndex:3];
                    NSLog(@"%@", self.groupId);
                    jiluBut.hidden = NO;
                }
                //                if ([obj isEqualToString:@"opq012"]) {
                //                    NSLog(@"%@-索引%d",obj, (int)idx);
                //
                //                }
                
            }];
        }
    }
    self.backItem.enabled = self.webView.canGoBack;
    self.forwardItem.enabled = self.webView.canGoForward;
    self.title = self.webView.title;
    self.progressView.progress = self.webView.estimatedProgress;
    self.progressView.hidden = self.webView.estimatedProgress >= 1;
}
-(void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
    
    //    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
    //
    //    [alertController addAction:([UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    //
    //        completionHandler();
    //
    //    }])];
    
    // [self presentViewController:alertController animated:YES completion:nil];
    
    
    
    
    
    
    NSLog(@"message================%@", message);
    
    
    
    if([message isEqualToString:@"支付成功"]){
        self.isPaySuccess = YES;
        completionHandler();
    }else if([message isEqualToString:@"中奖记录"]){
        
        
        NSLog(@"%@", message);
        //    self.ReturnValueBlock(self.idstr);
        
        HWjiluYaoQingliuzhangViewController *jilu = [[HWjiluYaoQingliuzhangViewController alloc]init];
        [self.navigationController pushViewController:jilu animated:YES];
        
        
        
        
        
        completionHandler();
        
        
    } else if([message isEqualToString:@"领取代金券"]){
        
        NSLog(@" %@", message);
        
        //        HWanGoldVolumeViewController *lingqu = [[HWanGoldVolumeViewController alloc]init];
        //        [self.navigationController pushViewController:lingqu animated:YES];
        //
        
        
        completionHandler();
        
        
        
    } else if([message isEqualToString:@"获取失败"]){
        
        NSLog(@" %@", message);
        [MBProgressHUD showtext:[NSString stringWithFormat:@"%@", message] icon:nil view:nil];
        
        //        HWanGoldVolumeViewController *lingqu = [[HWanGoldVolumeViewController alloc]init];
        //        [self.navigationController pushViewController:lingqu animated:YES];
        //
        
        
        completionHandler();
        
        
        
    }else {
        
        if([message containsString:@"提示:"]){
            
            
            [MBProgressHUD showtext:[NSString stringWithFormat:@"%@", [message substringFromIndex:3]] icon:nil view:nil];
            
            
        } else if ([message containsString:@"gid"]){
            HWGameDetailController *game = [[HWGameDetailController alloc] init];
            game.gameId = [message substringFromIndex:4];
            [self.navigationController pushViewController:game animated:YES];
        } else if ([message containsString:@"shequ_id"]){
            HWGameCommunityController *community = [[HWGameCommunityController alloc] init];
            community.communityId = [message substringFromIndex:9];
            [self.navigationController pushViewController:community animated:YES];
        } else if ([message containsString:@"tuijianqunliao"]){
            HWGroupChatRecommendController *chat = [[HWGroupChatRecommendController alloc] init];
            [self.navigationController pushViewController:chat animated:YES];
        }
        
        
        //          NSLog(@"订单 ：%@", message);
        //
        //        if([message containsString:@"order"]){
        //
        //            NSLog(@"订单 ：%@", message);
        //            NSString *strUrl = [message stringByReplacingOccurrencesOfString:@"order" withString:@""];
        //            NSLog(@"你是 %@",strUrl);
        //
        //            self.idstr = strUrl;
        //
        //
        //            self.ReturnValueBlock(self.idstr);
        //
        //
        //
        //
        //        }
        //
        completionHandler();
        
        
        
    }
    
    
    
    
    
    
    
    
    
}
#pragma mark - 对象被销毁
- (void)dealloc
{
    [self.webView removeObserver:self forKeyPath:@"canGoBack"];
    [self.webView removeObserver:self forKeyPath:@"title"];
    [self.webView removeObserver:self forKeyPath:@"canGoForward"];
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
    [self.webView removeObserver:self forKeyPath:@"URL"];
}



- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    
    
    if (!navigationAction.targetFrame.isMainFrame) {
        [webView evaluateJavaScript:@"var a = document.getElementsByTagName('a');for(var i=0;i<a.length;i++){a[i].setAttribute('target','');}" completionHandler:nil];
    }
    NSURL *url = navigationAction.request.URL;
    if ([url.absoluteString containsString:@"alipay"] || [url.absoluteString containsString:@"weixin"] || [url.absoluteString containsString:@"mqqwpa"]) {
        if (url.scheme != nil) {
            if ([url.scheme  isEqual: @"weixin"]) {
                NSLog(@"微信支付");
                [self catchEvent:url];
                decisionHandler(WKNavigationActionPolicyAllow);
                return;
            } else if ([url.scheme isEqualToString:@"alipay"]) {
                NSLog(@"支付宝支付");
                [self catchEvent:url];
                decisionHandler(WKNavigationActionPolicyAllow);
                return;
            } else if ([url.scheme isEqualToString:@"mqqwpa"]) {
                NSLog(@"支付宝支付");
                [self catchEvent:url];
                decisionHandler(WKNavigationActionPolicyAllow);
                return;
            }
        }
    }
    decisionHandler(WKNavigationActionPolicyAllow);
}

- (void)catchEvent:(NSURL *)eventUrl {
    if ([eventUrl.host isEqualToString:@"wap"] || [eventUrl.host isEqualToString:@"alipayclient"] || [eventUrl.host isEqualToString:@"dl"] || [eventUrl.host isEqualToString:@"mqqwpa"]) {
        if (@available(iOS 10.0, *)) {
            [[UIApplication sharedApplication] openURL:eventUrl options:@{} completionHandler:nil];
        } else {
            [[UIApplication sharedApplication] openURL:eventUrl];
        }
    } else {
        [[UIApplication sharedApplication] openURL:eventUrl options:@{} completionHandler:nil];
    }
}









@end
